package com.example.onlinetaxi.ui.activity.LauncherPage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverGetCancelThread;
import com.example.onlinetaxi.callback.DriverCallBack.ICancelDrive;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.dto.OrderDto.CompletedOrderDto;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.DriverMainActivity;
import com.example.onlinetaxi.ui.activity.GuidePage.GuideActivity;
import com.example.onlinetaxi.ui.activity.BaseActivity;
import com.example.onlinetaxi.ui.activity.MainPage.MainActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.SharedPreferenceUtil.Storage;
import com.example.onlinetaxi.view.Dialog.MyDialog;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;


// 启动页（闪屏页）
public class LauncherActivity extends BaseActivity {

    /**
     * 1.延时2000ms
     * 2.判断程序是否第一次运行
     * 3.Activity全屏主题
     */
    // 闪屏业延时
    private static final int HANDLER_SPLASH = 1001;

    // 请求参数
    private Map<String, String> map = new HashMap<>();
    // 响应体
    private DataResponse dataResponse;


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_SPLASH:
                    //判断程序是否是第一次运行
                    if (isFirst()) {
                        // 第一次登录
                        startActivity(new Intent(LauncherActivity.this, GuideActivity.class));
                    } else {
                        // 不是第一次使用，直接进入登录状态，跳转到打车页面
                        if (LocalStorage.type.equals("passenger")) {
                            // 跳转到乘客界面
                            startActivity(new Intent(LauncherActivity.this, MainActivity.class));
                        } else if (LocalStorage.type.equals("driver")) {
                            // 跳转到司机界面
                            startActivity(new Intent(LauncherActivity.this, DriverMainActivity.class));
                        }
                    }
                    finish();
                    break;
                default:
                    break;
            }
            return false;
        }

    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        initView();

    }

    //初始化View
    private void initView() {
        //延时2000ms
        handler.sendEmptyMessageDelayed(HANDLER_SPLASH, 2000);
    }

    // 判断程序是否第一次运行
    private boolean isFirst() {
        String phone = Storage.getString(this, "phone");

        LocalStorage.phone = phone;

        if (!phone.equals("")) {
            // 向后端发送请求，传递一个phone
            map.put("phone", phone);

            // 判断用户是否处于登录状态
            String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "login", "isLogin");
            // 获取响应体
            dataResponse = GetDataResponse.getDataResponse(response);

            if (dataResponse.getCode() == null) {
                return true;
            } else if (dataResponse.getCode().equals("200")) {
                // 获取用户类型
                LocalStorage.type = dataResponse.getData().get("type").toString();

                // 获取当前用户是否存在未完成订单
                String response2 = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "getCurrentOrder");
                DataResponse dataResponse = GetDataResponse.getDataResponse(response2);

                if (dataResponse.getCode().equals("200")) {
                    // 用户存在未完成订单
                    LocalStorage.currentOrderId = dataResponse.getData().get("orderId").toString();
                    Gson gson = new Gson();
                    LocalStorage.currentOrder = gson.fromJson(dataResponse.getData().get("order").toString(), CompletedOrderDto.class);

                    if (LocalStorage.type.equals("passenger")) {
                        if (LocalStorage.currentOrder.getState().equals("0")) {
                            Toast.makeText(this, "您有正在叫车的订单，请及时查看~", Toast.LENGTH_LONG).show();
                        } else if (LocalStorage.currentOrder.getState().equals("3")) {
                            Toast.makeText(this, "司机正在接您的路上，请时刻关注~", Toast.LENGTH_LONG).show();
                        } else if (LocalStorage.currentOrder.getState().equals("4")) {
                            Toast.makeText(this, "司机正在带您前往终点，请注意乘车安全~", Toast.LENGTH_LONG).show();
                        } else if (LocalStorage.currentOrder.getState().equals("7")) {
                            Toast.makeText(this, "您有正在未付款的订单，请及时查看~", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        if (LocalStorage.currentOrder.getState().equals("3") && !LocalStorage.currentOrder.getCancelState().equals("2")) {
                            Toast.makeText(this, "您有正在接车的订单，请时刻关注~", Toast.LENGTH_LONG).show();

                            // 如果订单没有被撤销，开启检测线程
//                            if (DriverGetCancelThread.thread == null) {
//                                // 司机启动线程，监视订单状态，以防乘客取消
//                                DriverGetCancelThread.iCancelDrive = new ICancelDrive() {
//                                    @Override
//                                    public void cancelDrive(String cancelReason) {
//                                        // 弹出确认对话框
//                                        showCancelDialog(cancelReason);
//                                    }
//                                };
//                                DriverGetCancelThread.finished = false;
//                                DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
//                                DriverGetCancelThread.thread.start();
//                            }
                        } else if (LocalStorage.currentOrder.getState().equals("4")) {
                            Toast.makeText(this, "您正送乘客前往目的地，请注意行车安全~", Toast.LENGTH_LONG).show();
                        }
                    }
                }

                // 用户不是第一次登录
                return false;
            }

        }
        // 用户尚未注册（第一次启动程序）
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void showCancelDialog(String cancelReason) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拒绝用户的请求
                disagree();

                // 重新启动线程
                DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
                DriverGetCancelThread.thread.start();
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 同意用户的请求
                agree();
            }
        };

        if (cancelReason.equals("")) {
            cancelReason = "无";
        }

        // 显示提示框
        Looper.prepare();
        MyDialog.drawable = getBaseContext().getDrawable(R.drawable.dialog_confirm_driver);
        if (!this.isFinishing()){
            MyDialog.showInfoDialog(this, "用户申请取消订单，理由:" + cancelReason, "拒绝", onCancelClickListener, "同意", onConfirmClickListener);
        }
        Looper.loop();
    }

    private void agree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "2");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;

        // 删除保存本地的订单数据
        LocalStorage.chosenOrder = null;
        LocalStorage.currentOrderId = null;
        LocalStorage.currentOrder = null;
    }

    private void disagree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "3");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;
    }

}